<template>
  <div>
    <div style="margin:0 auto; width:900px; font-size:14px;">
      <div class="headFixed">
        <el-row :gutter="20">
          <el-col :span="10">
            <div style="padding-left:20px;padding-top:10px">
              <span style="font-weight:bold">填写人：</span>
              <span style="color:#444444">{{questionData.fillInRealName}}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div style="padding-left:20px;padding-top:10px">
              <span style="font-weight:bold">耗时：</span>
              <span style="color:#444444">{{useTime}}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="padding-left:20px;padding-top:10px">
              <el-row>
                <el-col span="5">
                  <span style="font-weight:bold">进度：</span>
                </el-col>
                 <el-col span="18">
                   <el-progress :text-inside="true" :stroke-width="16"  :percentage="progress"></el-progress>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="headImg">
      <img src="img/bg/head.png" />
    </div>
    <div v-if="isValid" class="sheetContent">
      <div class="headStyle">
        {{ questionData.questionnaireTitle }}
      </div>
      <div class="noticeStyle">
        <div v-html="questionData.questionnaireNotice"></div>
      </div>
      <div v-for="(item, index) in data" :key="index" class="itemStyle">
        <div v-if="item.subjectProperties == '主题目'" class="titleStyle">
          <span style="color: red; font-weight: bold">
            {{ item.isRequired == "1" ? "*" : "" }}
          </span>
          {{ item.showSeq }}. {{ item.subjectTitle }}
          <span style="color: #666666; font-weight: normal; font-size: 14px">{{
            item.score > 0 && questionSheet ? "【" + parseInt(item.score) + "分】" : ""}}</span>
        </div>
        <div v-if="item.subjectProperties == '分割内容'" class="splitStyle">
          <el-divider content-position="left">{{item.subjectAnswer}}</el-divider>
        </div>
        <div style="padding-left: 20px">
          <div v-if="item.subjectType == '文本'">
            <el-input
              v-if="item.subjectProperties == '主题目'"
              :disabled="questionData.status > '1'"
              placeholder="请输入内容"
              v-model="item.answerResult"
              @change="changeUpdate(item)"
              style="width: 800px"
              clearable
            >
            </el-input>
          </div>
          <div v-if="item.subjectType == '多行文本'">
            <el-input
              v-if="item.subjectProperties == '主题目'"
              :disabled="questionData.status > '1'"
              type="textarea"
              rows="3"
              placeholder="请输入内容"
              v-model="item.answerResult"
              @change="changeUpdate(item)"
              style="width: 800px"
              clearable
            >
            </el-input>
          </div>
          <div v-if="item.subjectType == '数字'">
            <el-input
              v-if="item.subjectProperties == '主题目'"
              :disabled="questionData.status > '1'"
              type="number"
              placeholder="请输入内容"
              v-model="item.answerResult"
              @change="changeUpdate(item)"
              style="width: 800px"
              clearable
            >
            </el-input>
          </div>
          <div v-if="item.subjectType == '下拉选择'"></div>
          <div v-if="item.subjectType == '日期'">
            <el-date-picker
              v-if="item.subjectProperties == '主题目'"
              :disabled="questionData.status > '1'"
              v-model="item.answerResult"
              type="date"
              @change="changeUpdate(item)"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 800px"
            >
            </el-date-picker>
          </div>
          <div v-if="item.subjectType == '单选'">
            <el-radio-group
              v-if="item.subjectProperties == '主题目'"
              v-model="item.answerResult"
              @change="changeUpdate(item)"
            >
              <el-radio
                v-for="(subjectItem, indx) in item.subjectContent"
                :label="questionSheet ? subjectItem.label : subjectItem.value"
                :key="indx"
                :disabled="questionData.status > '1'"
                style="display: block; width: 700px"
                >
                {{ questionSheet ? subjectItem.label + "、" : ""}}{{ subjectItem.value }}
                </el-radio>
            </el-radio-group>
          </div>
          <div v-if="item.subjectType == '多选'">
            <el-checkbox-group
              v-if="item.subjectProperties == '主题目'"
              v-model="item.answerResult"
              @change="changeUpdate(item)"
            >
              <el-checkbox
                v-for="(subjectItem, indx) in item.subjectContent"
                :label="questionSheet ? subjectItem.label : subjectItem.value"
                :key="indx"
                :disabled="questionData.status > '1'"
                style="display: block; width: 700px"
                >
                {{ questionSheet ? subjectItem.label + "、" : ""}}{{ subjectItem.value }}
                </el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-if="item.subjectType == '地区'">
            <el-cascader
              v-if="item.subjectProperties == '主题目'"
              :disabled="questionData.status > '1'"
              size="large"
              :options="options"
              v-model="item.answerResult.selectedOptions"
              style="width: 800px"
              @change="handleChange(item)"
            >
            </el-cascader>
          </div>
          <div v-if="item.subjectType == '文件'">
            <el-upload
              v-if="item.subjectProperties == '主题目'"
              :disabled="questionData.status > '1'"
              class="upload-demo"
              action="/file/upload"
              :headers="headersParam"
              :data="dataParam"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="10"
              drag
              :on-success="handleSuccess"
              :on-change="handlelSaveFile(item)"
              :file-list="fileList"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </div>
        </div>
      </div>
      <div style="text-align: center">
        <el-button type="primary" @click="savaQuestionData" :disabled="questionData.status > '1'"> 提交 </el-button>
      </div>
    </div>
    <div style="text-align: center; padding-bottom: 50px; font-size: 14px">
      XXXX <span style="color: #666666"> 提供技术支持</span>
    </div>
  </div>
</template>

<script>
import {
  saveOrUpdateBizQuestionSendSubject,
  saveOrUpdateBizQuestionSendSubjectList,
  saveBizQuestionSendSubject,
  saveBizQuestionSendSubjectList,
  deleteBizQuestionSendSubject,
  queryBizQuestionSendSubject,
  queryBizQuestionSendSubjectListPage,
  updateBizQuestionSendSubject,
  deleteBizQuestionSendSubjectList,
} from '@/api/biz/question/bizQuestionSendSubjectApi';
import {
  saveBizQuestionSendList,
  saveBizQuestionSendListList,
  queryBizQuestionSendList,
  queryBizQuestionSendListListPage,
  updateBizQuestionSendList,
  deleteBizQuestionSendListList,
} from '@/api/biz/question/bizQuestionSendListApi';
import { mapGetters } from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import { regionData, CodeToText } from 'element-china-area-data';
import { getToken } from '@/util/auth';
import { Base64 } from 'js-base64';
import NProgress from 'nprogress';
export default {
  data() {
    return {
      //进度
      progress: 0,
      //耗时统计
      useTime: '0分0秒',
      seconds: 0,
      //页面是否有效
      isValid: true,
      //上传文件
      headersParam: {},
      dataParam: {},
      fileList: [],
      uploadFlag: '0',

      // 地址选择栏
      options: regionData,
      addtions: {}, //存储地址数据
      // 试卷类型
      questionSheet: false,
      checkList: [],
      loading: false,
      radio: '',
      data: [],
      questionData: {},
      questionSheetId: '',
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition: [],
        orderRule: [],
        currentPage: 1,
        pageSize: 10,
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {},
    };
  },
  computed: {
    ...mapGetters([
      'website',
      'orgTree',
      'genOrgTree',
      'userInfo',
      'permission',
      'projectInfo',
    ]),
  },
  methods: {
    /**
     * 加载下发列表信息
     */
    loadSendList() {
      this.reqParams = {
        singleBody: {
          id: this.questionSheetId,
        },
      };
      let commonData = reqCommonMsg(this.reqParams);
      queryBizQuestionSendList(commonData).then((res) => {
        this.questionData = res.data.body.singleBody;
        if (this.questionData.questionnaireType == '试卷') {
          this.questionSheet = true;
        }
        this.seconds = this.questionData.takeTime;
      },
      (error) => {
        this.$console.log(error);
      }
      );
    },
    /**
     * 处理地区
     */
    handleChange(value) {
      //我们选择地址后，selectedOptions 会保存对应的区域码，例如北京的区域码为'110000'
      //我们要取出区域码对应的汉字，就需要用CodeToText(区域码)进行输出
      this.$console.log('value===', value);
      this.addtions.selectedOptions = value.answerResult.selectedOptions;
      var name = '';
      value.answerResult.selectedOptions.map(
        (item) => (name += CodeToText[item] + '/')
      );
      this.addtions.names = name;
      value.answerResult = this.addtions;
      this.changeUpdate(value);
    },
    /**
     * 加载题目列表数据
     */
    onLoad(page) {
      this.reqParams = {
        singleBody: {
          questionnaireId: this.questionSheetId,
        },
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: {
          prop: 'showSeq',
          order: 'ascending',
        },
        currentPage: 1,
        pageSize: 99999,
      };
      this.commonData = reqCommonMsg(this.reqParams);
      queryBizQuestionSendSubjectListPage(this.commonData).then((res) => {
        const data = res.data.body;
        this.data = data.listBody;
        let index = 0;
        if(this.data.length == 0){
          this.$message({
            type: 'warning',
            message: '题目不存在，请联系管理员!'
          });
        }
        this.data.forEach((element) => {
          element.subjectContent = JSON.parse(element.subjectContent);
          if (
            element.subjectType == '多选' ||
              element.subjectType == '地区' ||
              element.subjectType == '文件'
          ) {
            element.answerResult = JSON.parse(element.answerResult);
          }

          //处理跳转题目
          let notGotoSubjectIds = [];
          let gotoSubjectId = '';
          //查找需要跳转的ID
          element.subjectContent.forEach((element2) => {
            if (this.questionSheet) {
              //试卷 比较label
              if (element2.label == element.answerResult) {
                gotoSubjectId = element2.gotoSubject;
              } else {
                notGotoSubjectIds.push(element2.gotoSubject);
              }
            } else {
              //问卷比较项值
              if (element2.value == element.answerResult) {
                gotoSubjectId = element2.gotoSubject;
              } else {
                notGotoSubjectIds.push(element2.gotoSubject);
              }
            }
          });
          //需要跳转的
          this.data.forEach((element3) => {
            if (element3.id == gotoSubjectId) {
              element3.subjectProperties = '主题目';
            }
          });
          //不需要跳转的
          notGotoSubjectIds.forEach((notElement) => {
            this.data.forEach((element3) => {
              if (element3.id == notElement) {
                element3.subjectProperties = '跳转题目';
                if (
                  element3.subjectType == '多选' ||
                    element3.subjectType == '地区' ||
                    element3.subjectType == '文件'
                ) {
                  element3.answerResult = [];
                } else {
                  element3.answerResult = '';
                }
              }
            });
          });
          if (element.subjectProperties == '主题目') {
            index++;
            element.showSeq = index;
          }
        });
        this.loading = false;
        this.computedProgress();
      },
      (error) => {
        this.loading = false;
      }
      );
    },

    /**
     * 计算完成进度
     */
    computedProgress(){
      let doCnt=0;
      let allCnt=0;
      this.data.forEach((element) => {
        if(element.subjectProperties == '主题目') {
          allCnt++;
          if(element.answerResult != '' && element.answerResult != '[]') {
            doCnt++;
          }
        }
      });
      this.progress = parseInt(doCnt * 100 / allCnt);
    },
    /**
     * 修改一条记录
     */
    changeUpdate(item) {
      //计算进度
      this.computedProgress();
      //处理跳转题目
      let notGotoSubjectIds = [];
      let gotoSubjectId = '';
      //查找需要跳转的ID
      item.subjectContent.forEach((element) => {
        if (this.questionSheet) {
          //试卷 比较label
          if (element.label == item.answerResult) {
            gotoSubjectId = element.gotoSubject;
          } else {
            notGotoSubjectIds.push(element.gotoSubject);
          }
        } else {
          //问卷比较项值
          if (element.value == item.answerResult) {
            gotoSubjectId = element.gotoSubject;
          } else {
            notGotoSubjectIds.push(element.gotoSubject);
          }
        }
      });
      //不需要跳转的
      notGotoSubjectIds.forEach((notElement) => {
        this.data.forEach((element) => {
          if (element.id == notElement) {
            element.subjectProperties = '跳转题目';
          }
        });
      });

      //需要跳转的
      let index = 0;
      this.data.forEach((element) => {
        if (element.id == gotoSubjectId) {
          element.subjectProperties = '主题目';
        }
        if (element.subjectProperties == '主题目') {
          index++;
          element.showSeq = index;
        }
      });

      //更新记录
      if(!item.answerResult || item.answerResult == null || item.answerResult == 'null'){
        item.answerResult = '';
      }
      this.reqParams.singleBody = item;

      this.commonData = reqCommonMsg(this.reqParams);
      updateBizQuestionSendSubject(this.commonData).then(
        (res) => {
          item = res.data.body.singleBody;
          this.data.forEach((element) => {
            if (element.id == item.id) {
              element.dataSign = item.dataSign;
            }
          });
          this.singleBody = {};
          this.$console.log('====记录保存成功！');
        },
        (error) => {
          this.$console.log(error);
        }
      );

      //更新进度
      if(this.questionData.beginDatetime == ''){
        this.questionData.beginDatetime = this.$toolUtil.formatTimes(new Date())
      }
      this.questionData.progressRate = this.progress;
      this.questionData.takeTime = this.seconds;
      this.questionData.status = '1';
      this.reqParams.singleBody = this.questionData;
      // 解析用户名（用户ID）
      this.commonData = reqCommonMsg(this.reqParams)
      updateBizQuestionSendList(this.commonData).then((res) => {
        this.questionData = res.data.body.singleBody;
        // this.$message({
        //   type: 'success',
        //   message: '操作成功!'
        // });
      }, error => {
        this.$console.log(error);
      });
    },

    /**
     * 上传成功回调
     */
    handleSuccess(response, file, fileList) {
      if(!response.head){
        this.fileList = [];
        this.$message({
          type: 'error',
          message: '文件上传错误，请联系管理员！',
        },5000);
      }
      else if (response.head.respCode == 'S0000') {
        var dataList = [];
        fileList.forEach((element) => {
          if (element.response) {
            if (element.status == 'success') {
              dataList.push({
                name: element.response.fileName,
                url: element.response.filePath,
                size: element.response.fileSize,
                type: element.response.fileType,
              });
            }
          } else if (element.name) {
            dataList.push(element);
          }
        });
        this.fileList = dataList;
        this.uploadFlag = '1';
      } else {
        file.status = 'error';
        this.$message({
          customClass: 'zZindex',
          type: 'error',
          message: response.respMsg,
        });
      }
    },
    /**
     * 保存记录
     */
    handlelSaveFile(currItem) {
      //
      if (this.uploadFlag == '1') {
        var dataList = [];
        if (this.fileList.length > 0) {
          this.fileList.forEach((element, index) => {
            if (element.response) {
              if (element.status == 'success') {
                dataList.push({
                  name: element.response.fileName,
                  url: element.response.filePath,
                  size: element.response.fileSize,
                  type: element.response.fileType,
                });
              }
            } else if (element.name) {
              dataList.push(element);
            }
          });
        }
        currItem.answerResult = dataList;
        this.$console.log('item.answerResult==', dataList);
        setTimeout(() => {
          this.changeUpdate(currItem);
        }, 2000);
        this.uploadFlag = '0';
      } else {
        this.fileList = currItem.answerResult;
      }
    },
    /**
     * 下载文件
     */
    handlePreview(file) {
      let href = 'http://fastdfs.dooleen.com:8888/' + file.url;
      window.open(href, '_blank');
    },

    /**
     * 保存问卷信息
     */
    savaQuestionData() {
      //检查必填项是否已完成
      let fillAll = true;
      let notDoNo = '';
      let index=0;
      let notDoCnt=0;
      this.data.forEach((element) => {
        if(element.subjectProperties == '主题目'){
          index++;
        }
        if(element.subjectProperties == '主题目' && element.isRequired == '1') {
          if(element.answerResult == '' || element.answerResult == '[]') {
            fillAll = false; 
            if(notDoCnt == 0)
            {
              notDoNo = index;
            }
            else{
              notDoNo = notDoNo + ', ' + index;
            }
            notDoCnt++
          }
        }
      });
      if(!fillAll){
        this.$message({
          type: 'warning',
          message: this.questionSheet? '试卷第'+notDoNo+'题还未完成!' : '问卷第'+notDoNo+'题还未完成!'
        });
        return false;
      }
      this.questionData.takeTime = this.seconds;
      this.questionData.status = '2';
      this.questionData.fillInDatetime = this.$toolUtil.formatTimes(new Date())
      this.reqParams.singleBody = this.questionData;
      // 解析用户名（用户ID）
      this.commonData = reqCommonMsg(this.reqParams)
      updateBizQuestionSendList(this.commonData).then(() => {
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        this.$console.log(error);
      });
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      let dicData = await this.$params.getBizDict('["bizType"]');
      this.findObject(this.option.column, 'bizType').dicData = dicData.bizType;
    },

    /**
     * 调用子组件方法查询历史
     */
    getHistoryRecord() {
      setTimeout(() => {
        this.$refs.historyRecord.getUpdateHistoryRecord(this.form.id);
      });
    },
  },
  created() {
    let urlParam = this.$toolUtil.UrlSearch();
    if (urlParam.qn) {
      this.questionSheetId = Base64.decode(urlParam.qn.replace(/%3D/g, '='));
      this.isValid = true;
    } else {
      this.isValid = false;
      alert('访问无效');
    }
  },
  mounted() {
    //初始化文件上传头信息
    this.headersParam = {
      Authorization: 'bearer ' + getToken(),
      UserId: this.userInfo.userId,
      UserSign: 'uploadFile',
      remote: 'no',
    };
    //加载问卷题单信息
    this.loadSendList();
    //加载数据
    this.onLoad(this.page);

    //统计耗时
    setInterval(() => {
      this.seconds++;
      var minutes = Math.floor(this.seconds / 60);
      var sec = this.seconds % 60;
      this.useTime= minutes + '分' + sec + '秒';
    }, 1000);
  },
};
</script>
<style  lang="scss">
html,
body,
#app {
  height: 100%;
  overflow: auto;
  margin: 0;
  padding: 0;
  background: #edf2f7 !important;
}
.headFixed {
  margin: 0 auto;
  width: 900px;
  position: fixed;
  background: #e0e0e0;
  z-index: 1000;
  border-bottom: 1px solid #7a7b7e;
  height: 40px;
}
.headImg {
  margin: 0 auto;
  width: 900px;
  padding-top: 40px;
}

.sheetContent {
  margin: 0 auto;
  width: 900px;
  margin-bottom: 50px;
  padding: 30px;
  background-color: #ffffff;
}

.headStyle {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
}
.noticeStyle {
  font-size: 14px;
  padding-top: 20px;
  line-height: 1.8;
}
.titleStyle {
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
  margin-bottom: 5px;
  padding: 5px 0px 5px 5px;
  // background-color: #eeeeee;
  background-image: linear-gradient(#eeeeee, #fff);
}
.itemStyle {
  margin-bottom: 50px;
}
</style>
